package com.tian.print.depot;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.tian.print.R;
import com.tian.print.ZxScanActivity;
import com.tian.print.app.AppConfig;
import com.tian.print.app.BaseActivity;
import com.tian.print.app.RepositoryManagerApp;
import com.tian.print.bean.CustomerMd;
import com.tian.print.bean.GoodsModel;
import com.tian.print.bean.KeyTypeMd;
import com.tian.print.bean.LocationMd;
import com.tian.print.bean.PersonMd;
import com.tian.print.bean.SaveResonpse;
import com.tian.print.bean.UseMd;
import com.tian.print.http.BaseObserver;
import com.tian.print.http.RxSchedulers;
import com.tian.print.http.request.ApiRequest;
import com.tian.print.http.response.Response;
import com.tian.print.utils.DateUtils;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

import static com.tian.print.app.RepositoryManagerApp.ConnectOrClose;

public class GoodsDetailActivity extends BaseActivity {

    private final static String TAG = GoodsDetailActivity.class.getSimpleName();

    private static final int REQUEST_CODE = 10000;

    /**
     * 仓库名字
     */
    @BindView(R.id.spinner_stock_name)
    NiceSpinner spinner_stock_name;

    /**
     * 用途
     */
    @BindView(R.id.spinner_use)
    NiceSpinner spinner_use;

    /**
     * 版长
     */
    @BindView(R.id.et_length)
    EditText et_length;

    /**
     * 旧料版号
     */
    @BindView(R.id.et_num)
    EditText et_num;

    /**
     * 周长
     */
    @BindView(R.id.et_girth)
    EditText et_girth;

    /**
     * 直径
     */
    @BindView(R.id.et_diameter)
    EditText et_diameter;

    /**
     * 数量 支数
     */
    @BindView(R.id.et_quantity)
    EditText et_quantity;

    /**
     * 外径
     */
    @BindView(R.id.et_out_radius)
    EditText et_out_radius;

    /**
     * 斜度
     */
    @BindView(R.id.et_dip_angle)
    EditText et_dip_angle;

    /**
     * 键宽
     */
    @BindView(R.id.et_key_specs)
    EditText et_key_specs;

    /**
     * 键深
     */
    @BindView(R.id.et_key_specs_two)
    EditText et_key_specs_two;

    /**
     * 键类型
     */
    @BindView(R.id.spinner_key_type)
    NiceSpinner spinner_key_type;

    @BindView(R.id.btn_print)
    Button btn_print;

    @BindView(R.id.btn_save)
    Button btn_save;

    @BindView(R.id.et_wifi_ip1)
    EditText et_ip1;

    @BindView(R.id.et_wifi_ip2)
    EditText et_ip2;

    @BindView(R.id.et_wifi_ip3)
    EditText et_ip3;

    @BindView(R.id.et_wifi_ip4)
    EditText et_ip4;

    @BindView(R.id.et_wifi_port)
    EditText et_port;

    @BindView(R.id.btn_wifi_connectandclose)
    Button btnConnectAndClose;

    @BindView(R.id.connect_ly)
    LinearLayout connect_ly;

    PrintConnectReceiver registerReceiver;

    private SaveResonpse currentSaveResonpse;

    @BindView(R.id.spinner_saleman)
    NiceSpinner spinner_saleman;

    @BindView(R.id.spinner_customer)
    TextView spinner_customer;

    @BindView(R.id.spinner_product_name)
    NiceSpinner spinner_product_name;

    private ArrayList<PersonMd> mPersonMds;
    private ArrayList<LocationMd> mLocationMds;
    private ArrayList<UseMd> mUseMds;
    private ArrayList<KeyTypeMd> mKeyTypeMds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        showLeftBack();
        setTitleShow("详细");
//        setRightButtonEnable("扫描");
//        setRightButtonListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                if (btn_print.isEnabled()) {
////                    Toast.makeText(GoodsDetailActivity.this, "请完成当前数据的打印", Toast.LENGTH_SHORT).show();
////                    return;
////                }
//                scanQRCode();
//            }
//        });

        setGoOnBtnListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (btn_save.isEnabled() || btn_print.isEnabled()) {
//                    Toast.makeText(GoodsDetailActivity.this, "请完成当前数据的保存或打印", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                onZxCodeReturn(null);
            }
        });

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());

        initViews();
        registerReceiver = new PrintConnectReceiver();
        registerReceiver(registerReceiver, new IntentFilter(AppConfig.PRINT_CONNECT));

        requestPermission();
    }

    private void initViews() {
        et_length.addTextChangedListener(new InnerTextWatcher(et_length));
        et_girth.addTextChangedListener(new InnerTextWatcher(et_girth));
        et_dip_angle.addTextChangedListener(new InnerTextWatcher(et_dip_angle));
        et_out_radius.addTextChangedListener(new InnerTextWatcher(et_out_radius));
        et_key_specs.addTextChangedListener(new InnerTextWatcher(et_key_specs));
        et_key_specs_two.addTextChangedListener(new InnerTextWatcher(et_key_specs_two));

        et_girth.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && !TextUtils.isEmpty(et_girth.getText().toString())) {
                    et_diameter.setText(String.format("%.2f", Double.parseDouble(et_girth.getText().toString()) / 3.14));
                }
            }
        });

        initSpinners();
    }

    private void initSpinners() {
        spinner_saleman.setBackgroundResource(R.drawable.textview_round_border);
        spinner_saleman.getPaint().setAntiAlias(true);//抗锯齿

        spinner_product_name.setBackgroundResource(R.drawable.textview_round_border);
        spinner_product_name.getPaint().setAntiAlias(true);//抗锯齿

        spinner_stock_name.setBackgroundResource(R.drawable.textview_round_border);
        spinner_stock_name.getPaint().setAntiAlias(true);//抗锯齿

        spinner_key_type.setBackgroundResource(R.drawable.textview_round_border);
        spinner_key_type.getPaint().setAntiAlias(true);//抗锯齿

        spinner_use.setBackgroundResource(R.drawable.textview_round_border);
        spinner_use.getPaint().setAntiAlias(true);//抗锯齿

        ApiRequest.apiClent.getPersonMds().compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<ArrayList<PersonMd>>() {
                    @Override
                    public void onSuccess(ArrayList<PersonMd> personMds) {
                        if (personMds == null || personMds.size() == 0)
                            return;

                        spinner_saleman.setText(personMds.get(0).toString());
                        spinner_saleman.setTag(personMds.get(0));

                        if (personMds.size() == 1) {
                            spinner_saleman.setEnabled(false);
                            return;
                        }

                        mPersonMds = personMds;
                        spinner_saleman.setEnabled(true);
                        spinner_saleman.attachDataSource(personMds);
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });


        ApiRequest.apiClent.getLocationMds().compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<ArrayList<LocationMd>>() {
                    @Override
                    public void onSuccess(ArrayList<LocationMd> locationMds) {
                        if (locationMds == null || locationMds.size() == 0)
                            return;

                        spinner_stock_name.setText(locationMds.get(0).toString());
                        spinner_stock_name.setTag(locationMds.get(0));

                        if (locationMds.size() == 1) {
                            spinner_stock_name.setEnabled(false);
                            return;
                        }

                        mLocationMds = locationMds;
                        spinner_stock_name.setEnabled(true);
                        spinner_stock_name.attachDataSource(locationMds);
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });

        ApiRequest.apiClent.getKeyType().compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<ArrayList<KeyTypeMd>>() {
                    @Override
                    public void onSuccess(ArrayList<KeyTypeMd> keyTypeMds) {
                        if (keyTypeMds == null || keyTypeMds.size() == 0)
                            return;

                        spinner_key_type.setText(keyTypeMds.get(0).toString());
                        spinner_key_type.setTag(keyTypeMds.get(0));

                        if (keyTypeMds.size() == 1) {
                            spinner_key_type.setEnabled(false);
                            return;
                        }

                        mKeyTypeMds = keyTypeMds;
                        spinner_key_type.setEnabled(true);
                        spinner_key_type.attachDataSource(keyTypeMds);
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });

        ApiRequest.apiClent.getUseMds().compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<ArrayList<UseMd>>() {
                    @Override
                    public void onSuccess(ArrayList<UseMd> useMds) {
                        if (useMds == null || useMds.size() == 0)
                            return;

                        spinner_use.setText(useMds.get(0).toString());
                        spinner_use.setTag(useMds.get(0));

                        if (useMds.size() == 1) {
                            spinner_use.setEnabled(false);
                            return;
                        }

                        mUseMds = useMds;
                        spinner_use.setEnabled(true);
                        spinner_use.attachDataSource(useMds);
                    }

                    @Override
                    public void onFailure(String msg) {
                    }
                });

        spinner_key_type.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (mKeyTypeMds == null) return;
                spinner_key_type.setTag(mKeyTypeMds.get(position));
            }
        });

        spinner_use.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (mUseMds == null) return;
                spinner_use.setTag(mUseMds.get(position));
            }
        });

        spinner_stock_name.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (mLocationMds == null) return;
                spinner_stock_name.setTag(mLocationMds.get(position));
            }
        });

        spinner_saleman.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (mPersonMds == null) return;
                spinner_saleman.setTag(mPersonMds.get(position));
            }
        });

    }


    class InnerTextWatcher implements TextWatcher {
        private String regex = "^\\d+.$";
        private EditText editText;

        public InnerTextWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Pattern r = Pattern.compile(regex);
            Matcher matcher = r.matcher(s);
            if (matcher.matches()) {
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(s.length() + 2)});
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @OnClick({R.id.btn_save, R.id.iv_qr_scale, R.id.btn_print, R.id.btn_wifi_connectandclose, R.id.spinner_customer})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.spinner_customer:

                if (spinner_saleman.getTag() == null) {
                    Toast.makeText(GoodsDetailActivity.this, "请先选择业务员", Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent = new Intent(GoodsDetailActivity.this, SelectCustomerActivity.class);
                intent.putExtra("personCode", ((PersonMd) spinner_saleman.getTag()).getPersonCode());
                startActivityForResult(intent, 100);
                break;

            case R.id.btn_save:
                postData();
                break;
            case R.id.iv_qr_scale:
                scanQRCode();
                break;

            case R.id.btn_print:
                if (ConnectOrClose == 0) {
                    connect_ly.setVisibility(View.VISIBLE);
                } else {
                    if (currentSaveResonpse == null) {
                        Toast.makeText(GoodsDetailActivity.this, "请先保存", Toast.LENGTH_LONG).show();
                        return;
                    }
                    //开始打印
                    startPrint();
//                    startPrint("");
                }
                break;

            case R.id.btn_wifi_connectandclose:
                int i = v.getId();
                if (i == com.postek.coyote.postekwifi.R.id.btn_wifi_connectandclose) {
                    if (ConnectOrClose == 0) {
                        String ip = et_ip1.getText().toString() + "." + et_ip2.getText().toString() + "." + et_ip3.getText().toString() + "." + et_ip4.getText().toString();
                        int port = Integer.parseInt(et_port.getText().toString());
                        RepositoryManagerApp.cdf.PTK_ConnectWiFi(ip, port);
                    }
                    if (ConnectOrClose == 1) {
                        RepositoryManagerApp.cdf.PTK_CloseConnectWiFi();
                        ConnectOrClose = 0;
                        btnConnectAndClose.setText(com.postek.coyote.postekwifi.R.string.connect);
                        Toast.makeText(GoodsDetailActivity.this, com.postek.coyote.postekwifi.R.string.unConnect, Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    private void postData() {
        if (!verifyInput())
            return;
        GoodsModel model = new GoodsModel();

        //存放位置
        model.setPlace(((LocationMd) spinner_stock_name.getTag()).getLocationID());
        //旧版版号
        model.setPlateNoOld(et_num.getText().toString());
        //用途
        model.setPlateOldUse(((UseMd) spinner_use.getTag()).getDataCode());
        //支数
        model.setQuantity(Integer.parseInt(et_quantity.getText().toString()));
        //版长
        model.setBanChang(TextUtils.isEmpty(et_length.getText().toString()) ? 0 : Double.parseDouble(et_length.getText().toString()));
        //周长
        model.setZhouChang(Double.parseDouble(et_girth.getText().toString()));
        //直径 et_diameter
        model.setZhiJing(Double.parseDouble(et_diameter.getText().toString()));

        //客户名
        if (spinner_customer.getTag() != null) {
            model.setCustomerCode(((CustomerMd) spinner_customer.getTag()).getCustomerCode());
        }

        //键宽
        if (!TextUtils.isEmpty(et_key_specs.getText().toString())) {
            model.setJianKuan(et_key_specs.getText().toString());
        }

        //键宽
        if (!TextUtils.isEmpty(et_key_specs_two.getText().toString())) {
            model.setJianShen(et_key_specs_two.getText().toString());
        }

        //键类型 et_key_type
        if (spinner_key_type.getTag() != null) {
            model.setJianLeiXing(((KeyTypeMd) spinner_key_type.getTag()).getDataCode());
        }

        //外径
        if (!TextUtils.isEmpty(et_out_radius.getText().toString())) {
            model.setDuTouWaiJing(Double.parseDouble(et_out_radius.getText().toString()));
        }

        //业务员 et_key_type
        if (spinner_saleman.getTag() != null) {
            model.setSaleman(((PersonMd) spinner_saleman.getTag()).getPersonCode());
        }

        //斜度
        if (!TextUtils.isEmpty(et_dip_angle.getText().toString())) {
            model.setXieDu(Double.parseDouble(et_dip_angle.getText().toString()));
        }


        //---------
        model.setUseState(0);
        model.setLastUpdatedBy(RepositoryManagerApp.getUserInfo().getAccount());
        model.setLastUpdateDate(DateUtils.getCurrentTime());

        ApiRequest.apiClent.saveMd(model)
                .compose(RxSchedulers.<Response<SaveResonpse>>compose())
                .subscribe(new BaseObserver<SaveResonpse>() {
                    @Override
                    public void onSuccess(SaveResonpse s) {
                        Log.i("saveMd", s.toString());
                        currentSaveResonpse = s;
                        Toast.makeText(GoodsDetailActivity.this, "保存成功,请点击打印开始打印", Toast.LENGTH_LONG).show();
                        btn_save.setEnabled(false);

                    }

                    @Override
                    public void onFailure(String msg) {
                        Log.i("saveMd_failer", msg);
                        Toast.makeText(GoodsDetailActivity.this, "保存失败", Toast.LENGTH_LONG).show();
                    }
                });
    }

    private boolean verifyInput() {
        boolean isVerify = true;

        if (spinner_stock_name.getTag() == null) {
            spinner_stock_name.setHint("请选择存放位置");
            isVerify = false;
        }

        if (TextUtils.isEmpty(et_num.getText().toString())) {
            et_num.setHint("请填写版号");
            isVerify = false;
        }

        if (spinner_use.getTag() == null) {
            spinner_stock_name.setHint("请选择用途");
            isVerify = false;
        }

        if (TextUtils.isEmpty(et_quantity.getText().toString())) {
            et_quantity.setHint("请填写支数");
            isVerify = false;
        }

        if (TextUtils.isEmpty(et_length.getText().toString())) {
            et_length.setHint("请填写版长");
            isVerify = false;
        }

        if (TextUtils.isEmpty(et_girth.getText().toString())) {
            et_girth.setHint("请填写周长");
            isVerify = false;
        }

//        if (spinner_customer.getTag() == null) {
//            spinner_customer.setHint("请选择客户");
//            isVerify = false;
//        }

        return isVerify;
    }

    /**
     * 打开二维码扫描
     * activity需要去重写onactivityforresult方法，具体请参考MainActivity
     */
    public void scanQRCode() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setCaptureActivity(ZxScanActivity.class);
        //底部的提示文字，设为""可以置空
        integrator.setPrompt("请扫描二维码");
        //前置或者后置摄像头
        integrator.setCameraId(0);
        //扫描成功的「哔哔」声，默认开启
        integrator.setBeepEnabled(true);
//                    integrator.setBarcodeImageEnabled(true);//是否保留扫码成功时候的截图
        integrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("Ok", "-requestCode-" + requestCode + ",resultCode-" + resultCode);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null)
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            else
                onZxCodeReturn(result.getContents());
        }
        //
        else {
            if (resultCode == 1122) {
                CustomerMd cmd = (CustomerMd) data.getSerializableExtra("select_customer");
                spinner_customer.setText(cmd.getNativeName());
                spinner_customer.setTag(cmd);
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    /**
     * 扫描字符串的格式 {"LocationID":"SH","LocationName":"田哈","IsId":2}
     *
     * @param result
     */
    public void onZxCodeReturn(String result) {
        currentSaveResonpse = null;
//        setRightButtonEnable("继续扫描");

        Gson gson = new GsonBuilder().create();
        LocationMd locationMd = null;
        try {
            locationMd = gson.fromJson(result, LocationMd.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (locationMd != null) {
            spinner_stock_name.setText(locationMd.getLocationName());
            spinner_stock_name.setTag(locationMd);
            spinner_stock_name.setEnabled(false);
        }
        btn_save.setEnabled(true);
        btn_print.setText("打印");
        btn_print.setEnabled(true);
        setInputEnable(true);
    }

    private void startPrint() {

        String showMsg = currentSaveResonpse.getPlateNoOld();

        Log.i(TAG, "thread-name = " + Thread.currentThread().getName());
        RepositoryManagerApp.cdf.PTK_ClearBuffer();
        RepositoryManagerApp.cdf.PTK_SetPrintSpeed(4);
        RepositoryManagerApp.cdf.PTK_SetDarkness(10);
        RepositoryManagerApp.cdf.PTK_SetDirection("T");
        RepositoryManagerApp.cdf.PTK_SetLabelWidth(600);
        RepositoryManagerApp.cdf.PTK_SetLabelHeight(240, 16, 0, false);


        String qrMsg = "\"" + showMsg + "\"";
        String liaoHaoMsg = "料号:" + showMsg;
        String guigeMsg = "版长:" + currentSaveResonpse.getBanChang();
        String zhouchang = "周长:" + currentSaveResonpse.getZhouChang();

//        int qrCode = RepositoryManagerApp.cdf.PTK_DrawBar2D_QR(350, 70, 100, 100, 0, 5, 4, 0, 0, qrMsg);
//        int txtCode = RepositoryManagerApp.cdf.PTK_DrawText(150, 110, 0, '2', 2, 2, 'N', showMsg);

        int qrCode = RepositoryManagerApp.cdf.PTK_DrawBar2D_QR(150, 50, 140, 140, 0, 7, 4, 0, 0, qrMsg);
        int txtCode = RepositoryManagerApp.cdf.PTK_DrawText(330, 20, 0, '2', 2, 2, 'N', liaoHaoMsg);
        int guigeCode = RepositoryManagerApp.cdf.PTK_DrawText(330, 90, 0, '2', 2, 2, 'N', guigeMsg);
        int zhouchangCode = RepositoryManagerApp.cdf.PTK_DrawText(330, 160, 0, '2', 2, 2, 'N', zhouchang);

        if (qrCode == 0 && txtCode == 0) {
            int printCode = RepositoryManagerApp.cdf.PTK_PrintLabel(1, 0);
            if (printCode == 0) {
                Toast.makeText(GoodsDetailActivity.this, "打印成功", Toast.LENGTH_LONG).show();
                currentSaveResonpse = null;
                btn_print.setText("点击\"继续\"");
                btn_print.setEnabled(false);
//                setRightButtonEnable("继续扫码");
                setInputEnable(false);
            } else {
                Toast.makeText(this, "打印失败，printCode = " + printCode, Toast.LENGTH_LONG).show();
            }

        } else {
            Toast.makeText(this, "打印失败，qrCode = " + qrCode, Toast.LENGTH_LONG).show();
        }

    }

    /**
     * 设置页面 可用与否
     *
     * @param enable
     */
    private void setInputEnable(boolean enable) {
        spinner_stock_name.setEnabled(enable);
        spinner_use.setEnabled(enable);
        et_length.setEnabled(enable);
        et_num.setEnabled(enable);
        et_girth.setEnabled(enable);
        et_diameter.setEnabled(enable);
        et_quantity.setEnabled(enable);
        et_out_radius.setEnabled(enable);
        et_dip_angle.setEnabled(enable);
        et_key_specs.setEnabled(enable);
        spinner_key_type.setEnabled(enable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(registerReceiver);
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int chec = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            if (chec != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        } else {
        }
    }

    class PrintConnectReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AppConfig.PRINT_CONNECT.equals(intent.getAction())) {
                if (ConnectOrClose == 1) {
                    btnConnectAndClose.setText(com.postek.coyote.postekwifi.R.string.disconnect);
                    connect_ly.setVisibility(View.GONE);
                    btn_print.setText("开始打印");
                } else {
                    startPrint();
                }
            }
        }
    }
}
